package com.mapaoer.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mapaoer.user.dao.DeveloperProfileRepository;
import com.mapaoer.user.dao.DeveloperSkillRepository;
import com.mapaoer.user.dao.SkillTagRepository;
import com.mapaoer.user.dto.DeveloperProfileDTO;
import com.mapaoer.user.entity.DeveloperProfile;
import com.mapaoer.user.entity.DeveloperSkill;
import com.mapaoer.user.entity.SkillTag;
import com.mapaoer.user.entity.User;
import com.mapaoer.user.service.DeveloperProfileService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 开发者资料服务实现类
 * 实现DeveloperProfileService接口定义的开发者资料相关业务操作
 */
@Service
public class DeveloperProfileServiceImpl implements DeveloperProfileService {

    @Autowired
    private DeveloperProfileRepository developerProfileRepository;

    @Autowired
    private SkillTagRepository skillTagRepository;

    @Autowired
    private DeveloperSkillRepository developerSkillRepository;

    @Override
    @Transactional
    public boolean createDeveloperProfile(DeveloperProfileDTO developerProfileDTO) {
        // 检查是否已存在该用户的开发者资料
        User user = new User();
        user.setId(developerProfileDTO.getUserId());
        QueryWrapper<DeveloperProfile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", developerProfileDTO.getUserId());
        if (developerProfileRepository.selectCount(queryWrapper) > 0) {
            return false;
        }

        DeveloperProfile developerProfile = new DeveloperProfile();
        BeanUtils.copyProperties(developerProfileDTO, developerProfile);
        user.setId(developerProfileDTO.getUserId());
        developerProfile.setUser(user);
        developerProfileRepository.insert(developerProfile);
        return true;
    }

    @Override
    @Transactional
    public boolean updateDeveloperProfile(Long id, DeveloperProfileDTO developerProfileDTO) {
        DeveloperProfile developerProfile = developerProfileRepository.selectById(id);
        if (developerProfile == null) {
            return false;
        }
        BeanUtils.copyProperties(developerProfileDTO, developerProfile);
        developerProfileRepository.updateById(developerProfile);
        return true;
    }

    @Override
    public DeveloperProfileDTO getDeveloperProfileById(Long id) {
        DeveloperProfile developerProfile = developerProfileRepository.selectById(id);
        if (developerProfile == null) {
            return null;
        }
        return convertToDTO(developerProfile);
    }

    @Override
    public DeveloperProfileDTO getDeveloperProfileByUserId(Long userId) {
        User user = new User();
        user.setId(userId);
        QueryWrapper<DeveloperProfile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        DeveloperProfile developerProfile = developerProfileRepository.selectOne(queryWrapper);
        if (developerProfile == null) {
            return null;
        }
        return convertToDTO(developerProfile);
    }

    @Override
    public List<DeveloperProfileDTO> searchDevelopers(String skills, Integer minExperience, String workType, Integer minAge, Integer maxAge) {
        QueryWrapper<DeveloperProfile> queryWrapper = new QueryWrapper<>();

        // 构建查询条件
        if (skills != null && !skills.isEmpty()) {
            queryWrapper.like("skills", skills);
        }
        if (minExperience != null) {
            queryWrapper.ge("work_experience_years", minExperience);
        }
        if (workType != null) {
            queryWrapper.eq("expected_work_type", workType);
        }
        if (minAge != null && maxAge != null) {
            queryWrapper.between("age", minAge, maxAge);
        }

        List<DeveloperProfile> profiles = developerProfileRepository.selectList(queryWrapper);

        return profiles.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public boolean addSkill(Long developerId, String skillName, String level, Integer experienceYears) {
        // 检查开发者是否存在
        DeveloperProfile developerProfile = developerProfileRepository.selectById(developerId);
        if (developerProfile == null) {
            return false;
        }

        // 获取或创建技能标签
        QueryWrapper<SkillTag> skillQueryWrapper = new QueryWrapper<>();
        skillQueryWrapper.eq("name", skillName);
        SkillTag skillTag = skillTagRepository.selectOne(skillQueryWrapper);
        if (skillTag == null) {
            skillTag = new SkillTag();
            skillTag.setName(skillName);
            skillTag.setCategory(SkillTag.SkillCategory.LANGUAGE);
            skillTag.setCreateTime(new Date());
            skillTagRepository.insert(skillTag);
        }

        // 检查技能是否已存在
        QueryWrapper<DeveloperSkill> dsQueryWrapper = new QueryWrapper<>();
        dsQueryWrapper.eq("developer_id", developerProfile.getId())
                      .eq("skill_id", skillTag.getId());
        if (developerSkillRepository.selectCount(dsQueryWrapper) > 0) {
            return false;
        }

        // 创建开发者技能关联
        DeveloperSkill developerSkill = new DeveloperSkill();
        developerSkill.setDeveloper(developerProfile);
        developerSkill.setSkill(skillTag);
        developerSkill.setLevel(DeveloperSkill.ProficiencyLevel.valueOf(level));
        developerSkill.setExperienceYears(experienceYears != null ? experienceYears : 0);
        developerSkill.setCreateTime(new Date());

        developerSkillRepository.insert(developerSkill);
        return true;
    }

    @Override
    @Transactional
    public boolean removeSkill(Long developerId, Long skillId) {
        DeveloperProfile developerProfile = developerProfileRepository.selectById(developerId);
        SkillTag skillTag = skillTagRepository.selectById(skillId);
        
        if (developerProfile == null || skillTag == null) {
            return false;
        }
        
        QueryWrapper<DeveloperSkill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("developer_id", developerProfile.getId())
                    .eq("skill_id", skillTag.getId());
        DeveloperSkill developerSkill = developerSkillRepository.selectOne(queryWrapper);
        if (developerSkill == null) {
            return false;
        }

        developerSkillRepository.deleteById(developerSkill.getId());
        return true;
    }

    /**
     * 将DeveloperProfile实体转换为DeveloperProfileDTO
     */
    private DeveloperProfileDTO convertToDTO(DeveloperProfile developerProfile) {
        DeveloperProfileDTO dto = new DeveloperProfileDTO();
        BeanUtils.copyProperties(developerProfile, dto);
        dto.setUserId(developerProfile.getUser().getId());

        // 获取开发者的技能列表
        QueryWrapper<DeveloperSkill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("developer_id", developerProfile.getId());
        List<DeveloperSkill> developerSkills = developerSkillRepository.selectList(queryWrapper);
        List<String> skills = new ArrayList<>();

        for (DeveloperSkill developerSkill : developerSkills) {
            SkillTag skillTag = skillTagRepository.selectById(developerSkill.getSkill().getId());
            if (skillTag != null) {
                skills.add(skillTag.getName());
            }
        }

        dto.setSkills(skills);
        return dto;
    }
}